<?php
namespace app\index\controller;
use think\Controller;

class User extends Controller
{
    public function login()
    {
    	//获取session值
    	$user = session('user','','index');
    	if($user && $user->id){
    		$this->redirect('index/index');
    	}
        return $this->fetch();
    }
    
    public function register()
    {
    	if(request()->isPost()){
    		$data = input('post.');
    		if(!captcha_check($data['verifycode'])){
    			$this->error('验证码错误');
    		}
    		//严格校验数据
    		if($data['password'] != $data['repassword']){
    			$this->error('两次输入密码不相同');
    		}
    		//自动生成，密码的加盐字符串
    		$data['code'] = mt_rand(100,10000);
    		$data['password'] = md5($data['password'].$data['code']);
    		try{
    			$userId = model('User')->add($data);
    		}catch(\Exception $e){
    			$this->error($e->getMessage());
    		}

    		if($userId){
    			$this->success('注册成功',url('index/index'));
    		}else{
    			$this->error('注册失败');
    		}
    	}else{
    		return $this->fetch();
    	}
    }

    public function logincheck(){
    	if(!request()->isPost()){
    		$this->error('提交不合法');
    	}
    	$data = input('post.');
    	//数据校验，晚点再完成

    	$user = model('user')->getUserByUsername($data['username']);
    	if(!$user || $user->status !=1){
    		$this->error('该用户不存在');
    	}

    	if(md5($data['password'].$user->code) != $user->password){
    		$this->error('用户名或密码错误');
    	}

    	//登陆成功
    	$res = model('User')->updateById(['lsat_login_time' => time()],$user->id);

    	//把用户信息记录到session
    	session('user',$user,'index');
		return $this->redirect('index/index');
    }

    public function loginout(){
    	session(null,'index');
    	$this->redirect('user/login');
    }
}
